import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Table, Button, Input, Grid, Form, Select, Message, Dialog, Breadcrumb } from '@alifd/next';
import '#/scss/Global.scss';
import './BindMetric.scss';
import { ApiOfMetricGroupGet, ApiOfMetricGroupBindMetrics, ApiOfMetricList } from '#/utils/coreApiDefine'
import Metric from '#/pages/Metric'

const { Row, Col } = Grid;

export default class BindMetric extends Component {
    static displayName = 'BindMetric';
    static propTypes = {};
    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            metricGroupCode: this.props.code || this.props.match.params.code,
            availableMetrics: [],
            availableMetricDS: [],
            reboundMetrics: [],
            selectedMetricId: '',
            selectMetricsDialogVisible: false,
            rowSelection: {
                onChange: this.onRowSelectChange.bind(this),
                selectedRows: [],
                selectedRowKeys: [],
                dirty: 2
            }
        };
    }

    componentDidMount() {
        let that = this;
        ApiOfMetricGroupGet(this.state.metricGroupCode).then(response => {
            let data = response.data;
            that.setState({
                reboundMetrics: data.metrics
            })
        })
    }

    renderMetricRule = (value, index, item) => {
        let that = this;
        if (!item.rule) {
            return (
                <div></div>
            );
        } else {
            let rule = JSON.parse(item.rule);
            return (
                <div>
                    {Object.keys(rule).map(function (k) {
                        return (
                            <dl key={k} style={styles.horizontal.dl}>
                                <dt style={styles.horizontal.dt}>{k}:</dt>
                                <dd style={styles.horizontal.dd}>{rule[k]}</dd>
                            </dl>
                        );
                    })}
                </div>
            );
        }
    }

    renderOper = (value, index, item) => {
        let that = this;
        return (
            <div>
                <Button onClick={() => this.onRemoveMetric(item)} type="primary" text style={{ color: '#ff3000' }}>{item.dirty == 1 ? '撤销' : '移除'}</Button>
            </div>
        );
    }
    // 选择模式时，选择项改变事件
    onRowSelectChange(ids, records) {
        const { rowSelection } = this.state;
        rowSelection.selectedRowKeys = ids;
        rowSelection.selectedRows = [...rowSelection.selectedRows, ...records]
        this.setState({ rowSelection });
    }

    // 选择模式时，选择好后的确认事件
    onSelectConfirm() {
        let possibleRows = this.state.rowSelection.selectedRows,
            selectedRowKeys = this.state.rowSelection.selectedRowKeys;
        let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1)
        this.props.onSelect(selectedRows)
    }

    onHandleSearchMetric = value => {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => {
            ApiOfMetricList({ s_name: value }).then(response => {
                const { data } = response;

                let metricKPs = data.map(function (item) {
                    return { value: item.id, label: item.name };
                });
                this.setState({
                    availableMetrics: data,
                    availableMetricDS: metricKPs,
                });
            }).catch(error => {
                console.log(error);
            })
        }, 100);
    }

    onHandleChangeMetric = value => {
        this.setState({ selectedMetricId: value })
    }

    // dirty undefined/-1/0:无操作 1:准备移除 2：新添加
    onRemoveMetric = metric => {
        let reboundMetrics = this.state.reboundMetrics
        let _metric = reboundMetrics.find(item => item.id === metric.id);
        if (_metric.dirty == 2) {
            reboundMetrics.splice(reboundMetrics.findIndex(item => item.id === _metric.id), 1);
        } else if (_metric.dirty == 1) {
            delete _metric.dirty;
        } else {
            _metric.dirty = 1;
        }
        this.setState({ reboundMetrics })
    }
    onBatchRemove = () => {
        let rowSelection = this.state.rowSelection;
        let selectedRowKeys = rowSelection.selectedRowKeys;
        let reboundMetrics = this.state.reboundMetrics;
        rowSelection.dirty = 2;
        selectedRowKeys.forEach(function (value, index) {
            let _metric = reboundMetrics.find(item => item.id === value);
            if (_metric) {
                if (_metric.dirty == 1) {
                    delete _metric.dirty;
                } else {
                    _metric.dirty = 1;
                    rowSelection.dirty = 1;
                }
            }
        });
        this.setState({ reboundMetrics });
        this.setState({ rowSelection });
    }
    onAddMetric = () => {
        let selectedMetric = this.state.availableMetrics.find(value => value.id == this.state.selectedMetricId);
        let index = this.state.reboundMetrics.findIndex(value => value.id == this.state.selectedMetricId);
        if (index == -1) {
            selectedMetric.dirty = 2;// 标记为准备新加
            this.state.reboundMetrics.push(selectedMetric);
            this.setState({ reboundMetrics: this.state.reboundMetrics })
        } else {
            Message.warning('已经添加过了!');
        }
    }

    onBindMetrics = () => {
        let that = this;
        let reboundMetricCodes = this.state.reboundMetrics.filter(item => item.dirty != 1).map(item => item.code);
        ApiOfMetricGroupBindMetrics(this.state.metricGroupCode, reboundMetricCodes)
            .then(() => {
                Message.success('指标绑定成功!');
                this.props.history.push('/manage/metricgroup')
            })
    }

    onOpenSelectMetricsDialog = () => {
        this.setState({
            selectMetricsDialogVisible: true,
        });
    }


    onCloseSelectMetricsDialog = metrics => {
        console.log(metrics)
        let that = this;
        this.setState({
            selectMetricsDialogVisible: false
        });
        console.log(!Array.isArray(metrics))
        if (!Array.isArray(metrics)) return;

        metrics.forEach(metric => {
            let index = that.state.reboundMetrics.findIndex(value => value.id == metric.id);
            if (index == -1) {
                metric.dirty = 2;// 标记为准备新加
                that.state.reboundMetrics.push(metric);
                that.setState({ reboundMetrics: that.state.reboundMetrics })
            }
        })
    }

    setRowProps = (item, index) => {
        if (item.dirty === 1) {
            return {
                style: styles.willRemove,
            };
        } else if (item.dirty === 2) {
            return {
                style: styles.willAdd,
            };
        }
    }

    renderSummery = () => {
        let willAddCount = this.state.reboundMetrics.filter(item => item.dirty != 1).length;
        let willRemoveCount = this.state.reboundMetrics.length - willAddCount;
        let text = '待绑定：' + willAddCount + ' 个，' + '待移除：' + willRemoveCount + ' 个';
        return (
            <span>
                {text}
            </span>
        )
    }

    render() {

        let summery = this.renderSummery();
        let ActionBar =
            <div>
                <div style={styles.formItem}>
                    <div>
                        <Button onClick={this.onBindMetrics} type="primary" size="small" style={{ marginRight: 10 }} >提 交 </Button>
                    </div>
                    <div>
                        <Button onClick={() => this.onBatchRemove()} disabled={this.state.rowSelection.selectedRowKeys.length == 0} type="normal" size="small" style={{ marginRight: 10 }}>{this.state.rowSelection.dirty == 1 ? '撤销' : '移除'}</Button>
                    </div>
                    <div>
                        {summery}
                    </div>
                    <div>
                        <Button onClick={this.onOpenSelectMetricsDialog.bind(this)} size="small" style={{ marginLeft: 10 }}> 选择更多指标 </Button>
                    </div>
                </div>
            </div>

        return (
            <IceContainer style={styles.container}>
                <Row wrap gutter="20" style={styles.formRow}>
                    <Col l="24">
                        {ActionBar}
                    </Col>
                </Row>
                <Table
                    dataSource={this.state.reboundMetrics}
                    hasBorder={false}
                    getRowProps={this.setRowProps}
                    style={{ padding: '0 20px 20px' }}
                    rowSelection={this.state.rowSelection}
                >
                    <Table.Column width={200} title="名称" dataIndex="name" />
                    <Table.Column width={150} title="编号" dataIndex="code" />
                    <Table.Column width={180} title="变量名" dataIndex="variable" />
                    <Table.Column width={240} title="指令" dataIndex="command" />
                    <Table.Column
                        width={200}
                        title="解析规则"
                        dataIndex="rule"
                        cell={this.renderMetricRule}
                    />
                    <Table.Column
                        width={80}
                        title="操作"
                        cell={this.renderOper}
                    />
                </Table>
                <Row wrap gutter="20" style={styles.formRow}>
                    <Col l="24">
                        {ActionBar}
                    </Col>
                </Row>
                <Dialog
                    className="dialog-with-table"
                    style={{ width: '80%' }}
                    title="选择指标"
                    visible={this.state.selectMetricsDialogVisible}
                    footer={false}
                    shouldUpdatePosition={true}
                    onClose={this.onCloseSelectMetricsDialog}>
                    <Metric forSelectUsage={true} match={this.props.match} onSelect={this.onCloseSelectMetricsDialog} />
                </Dialog>
            </IceContainer>
        );
    }
}

const styles = {
    container: {
        margin: '20px',
        padding: '0 0 20px',
    },
    title: {
        margin: '0',
        padding: '15px 20px',
        fonSize: '16px',
        textOverflow: 'ellipsis',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        color: 'rgba(0,0,0,.85)',
        fontWeight: '500',
        borderBottom: '1px solid #eee',
    },
    link: {
        margin: '0 5px',
        color: 'rgba(49, 128, 253, 0.65)',
        cursor: 'pointer',
        textDecoration: 'none',
    },
    separator: {
        margin: '0 3px',
        display: 'inline-block',
        height: '12px',
        width: '1px',
        verticalAlign: 'middle',
        background: '#e8e8e8',
    },
    pagination: {
        textAlign: 'right',
        marginRight: '20px',
    },
    editIcon: {
        color: '#2874D1',
        cursor: 'pointer',
    },
    horizontal: {
        dl: {
            marginTop: '3px',
            marginBottom: '3px',
        },
        dt: {
            float: 'left',
            width: '10%',
            overflow: 'hidden',
            clear: 'left',
            textAlign: 'right',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
        },
        dd: {
            marginLeft: '12%',
        }
    },
    formItem: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
    },
    formItemRight: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
        float: 'right'
    },
    formComponent: {
        minWidth: '300px',
    },
    formLabel: {
        minWidth: '70px',
    },
    willAdd: {
        background: '#dff0d8'
    },
    willRemove: {
        background: '#f2dede'
    },
    formRow: {
        padding: '10px 20px',
    },
    formItem: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
    },
};